//
//  XXPageSelectorView.m
//  XXPageViewController
//
//  Created by yxlong on 15/5/19.
//  Copyright (c) 2015年 yixin. All rights reserved.
//

#import "XXPageSelectorView.h"
#import "JTCSM.h"

#define _bar_item_tag_base 30000
#define _bar_item_width self.frame.size.width/2
#define defaultSeparatorLineColor [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1]
#define defaultIndicatorColor [UIColor whiteColor]

@interface XXPageSelectorView ()
{
    CGFloat _barWidth;
    NSInteger widthOfNumber;
}

- (void)_cleanupItems;
@end

@implementation XXPageSelectorView
@synthesize separatorLineColor=_separatorLineColor;
@synthesize sourceItems=_sourceItems;

- (id)initWithFrame:(CGRect)frame
{
    if(self=[super initWithFrame:frame]){
        self.userInteractionEnabled = YES;
        
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.bounces = NO;
        [self addSubview:_scrollView];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame itemTitles:(NSArray *)array
{
    if(self=[self initWithFrame:frame]){
        self.sourceItems = array;
       
    }
    return self;
}

- (void)_cleanupItems
{
    for(UIView *v in _scrollView.subviews){
        if([v isKindOfClass:[XXPageSelectorItem class]]){
            [v removeFromSuperview];
        }
    }
}

- (void)setSourceItems:(NSArray *)array
{
    _sourceItems = array;
    _barWidth = KVIEWwith/array.count;
    widthOfNumber = array.count;
    [self _cleanupItems];
    if(_sourceItems.count>0){
        int i=0;
        for(NSString *title in _sourceItems){
            XXPageSelectorItem *btn = [[XXPageSelectorItem alloc] init];
            btn.tag = _bar_item_tag_base+i;
            btn.mytag = _bar_item_tag_base+i;
            [btn setTitle:title forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            btn.indicatorColor = defaultSeparatorLineColor;
            [btn addTarget:self action:@selector(_barItemSelect:) forControlEvents:UIControlEventTouchUpInside];
            [_scrollView addSubview:btn];
            btn.titleString = title;
            [btn.titleLabel setFont:[UIFont systemFontOfSize:14]];
            btn.frame = CGRectMake(i*_barWidth, 0, _barWidth, self.frame.size.height);
            
            i++;

            
            [df lineViewWithWidthtofLeft:KVIEW_X(btn)-0.5 superView:btn spacing:8 color:RGBACOLOR(241, 241, 241, 1) lineWidth:.5];
            [df lineViewWithWidthtofLeft:0 superView:btn spacing:8 color:RGBACOLOR(241, 241, 241, 1) lineWidth:.5];
            
        }
    }
    [_scrollView setContentSize:CGSizeMake(_barWidth*_sourceItems.count, self.frame.size.height)];
}

- (UIColor*)separatorLineColor
{
    if(_separatorLineColor){
        return _separatorLineColor;
    }
    return defaultSeparatorLineColor;
}

- (void)setSeparatorLineColor:(UIColor *)color
{
    _separatorLineColor = color;
    [self setNeedsDisplay];
}

- (void)_barItemSelect:(id)sender
{
    XXPageSelectorItem *btn = (XXPageSelectorItem *)sender;
    NSUInteger willSelectedIndex = btn.tag-_bar_item_tag_base;
    
    if(willSelectedIndex==_selectedIndex){
        return;
    }
    if(_block_didSelectedAtIndex){
        _block_didSelectedAtIndex(willSelectedIndex);
    }
}

- (void)setSelectedIndex:(NSUInteger)index
{
    UIButton *lastBtn = (UIButton *)[_scrollView viewWithTag:(_selectedIndex+_bar_item_tag_base)];
    lastBtn.selected = NO;
    
    _selectedIndex = index;
    
    UIButton *selectedBtn = (UIButton *)[_scrollView viewWithTag:(index+_bar_item_tag_base)];
    selectedBtn.selected = YES;
    
    UIView *willSelectedBarItem = [_scrollView viewWithTag:(index+_bar_item_tag_base)];
    CGRect visibleFrame = willSelectedBarItem.frame;
    visibleFrame.origin.x -= _barWidth*2;
    visibleFrame.size.width = CGRectGetWidth(self.frame);
    if (_sourceItems.count -index >=widthOfNumber) {
        [_scrollView setContentOffset:CGPointMake((index*selectedBtn.frame.size.width), 0) animated:YES];
    }else{
        [_scrollView setContentOffset:CGPointMake(((_sourceItems.count-widthOfNumber)*selectedBtn.frame.size.width), 0) animated:YES];

    }
//    [_scrollView scrollRectToVisible:visibleFrame animated:YES];
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    [RGBACOLOR(241, 241, 241, 1) setStroke];
    [bezierPath setLineWidth:1.0];
    
    [bezierPath moveToPoint:CGPointMake(0.0, 0.0)];
    [bezierPath addLineToPoint:CGPointMake(CGRectGetWidth(rect), 0.0)];
    [bezierPath stroke];
    
    [bezierPath moveToPoint:CGPointMake(0.0, CGRectGetHeight(rect))];
    [bezierPath addLineToPoint:CGPointMake(CGRectGetWidth(rect), CGRectGetHeight(rect))];
    [bezierPath stroke];
}

@end


@implementation XXPageSelectorItem

@synthesize indicatorColor=_indicatorColor;

- (UIColor *)indicatorColor
{
    if(_indicatorColor){
        return _indicatorColor;
    }
    return RGBACOLOR(241, 241, 241, 1);
}

- (void)setIndicatorColor:(UIColor *)color
{
    _indicatorColor = color;
    [self setTitleColor:color forState:UIControlStateSelected];
    
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    
    if (self.selected) {
        UIBezierPath *bezierPath = [UIBezierPath bezierPath];
        // Draw the indicator
//        [bezierPath moveToPoint:CGPointMake(0.0, CGRectGetHeight(rect) - 1.0)];
        
        CGRect myrect = [self.titleString boundingRectWithSize:CGSizeMake(10000, rect.size.height) options: NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14],NSFontAttributeName, nil] context:nil];
        // Draw the indicator
        [bezierPath moveToPoint:CGPointMake((rect.size.width-myrect.size.width)/2, CGRectGetHeight(rect)/4*3)];
        [bezierPath addLineToPoint:CGPointMake((rect.size.width-myrect.size.width)/2+myrect.size.width, CGRectGetHeight(rect)/4*3)];
        [bezierPath setLineWidth:2.0];
        [self.indicatorColor setStroke];
        [bezierPath stroke];
        
    }
}
- (UILabel *)label{
    if (!_label) {
        _label = [UILabel initWithFrame:CGRectZero text:@"" font:12 textAlignment:NSTextAlignmentCenter texcolor:[UIColor whiteColor] backgroundColor:RGBACOLOR(255, 24, 24, 1)];
        [df layerWithView:_label radius:7.5 width:0 color:nil];
        [_label bringSubviewToFront:self];
        [self addSubview:_label];
    }
    
    return _label;
}

@end

